<script setup lang="ts">
import type { TypedOptions } from "typed.js";
import dayjs from "dayjs";
import { computed, defineComponent, h, onBeforeUnmount, onMounted, ref } from "vue";
import { IconifyIcon as Icon } from "@/components/ReIcon";
import ReTyped from "@/components/ReTyped";
import { useUserStore } from "@/stores/user";

// ===================== 顶部问候与时间 =====================
const userStore = useUserStore();
const userName = computed(
    () => userStore.nickname || userStore.username || "用户",
);

const nowText = ref(dayjs().format("YYYY年MM月DD日 ddd HH:mm:ss"));
let timer: any = null;
onMounted(() => {
    timer = setInterval(() => {
        nowText.value = dayjs().format("YYYY年MM月DD日 ddd HH:mm:ss");
    }, 1000);
});
onBeforeUnmount(() => timer && clearInterval(timer));

const greeting = computed(() => {
    const h = dayjs().hour();
    if (h < 6) return "凌晨好";
    if (h < 9) return "早上好";
    if (h < 12) return "上午好";
    if (h < 14) return "中午好";
    if (h < 18) return "下午好";
    return "晚上好";
});

const typedOptions = ref<TypedOptions>({
    strings: [
        "欢迎使用现代化管理系统",
        "高效、简洁、可定制",
        "一切从首页开始",
    ],
    typeSpeed: 60,
    backSpeed: 30,
    backDelay: 1200,
    smartBackspace: true,
    loop: true,
});

// ===================== 统计卡数据 =====================
interface Kpi {
    title: string;
    value: number;
    unit?: string;
    delta?: string;
    icon: string;
    gradient: string; // tailwind 渐变类
}

const kpis = ref<Kpi[]>([
    {
        title: "今日访问",
        value: 12890,
        unit: "次",
        delta: "+12.3%",
        icon: "ep:trend-charts",
        gradient: "from-indigo-500 to-purple-500",
    },
    {
        title: "活跃用户",
        value: 842,
        unit: "人",
        delta: "+3.1%",
        icon: "ep:user",
        gradient: "from-emerald-500 to-teal-500",
    },
    {
        title: "转化率",
        value: 8.6,
        unit: "%",
        delta: "+0.6%",
        icon: "ep:pie-chart",
        gradient: "from-amber-500 to-orange-500",
    },
    {
        title: "系统消息",
        value: 17,
        unit: "条",
        delta: "-2",
        icon: "ep:bell-filled",
        gradient: "from-fuchsia-500 to-rose-500",
    },
]);

// ===================== 快捷入口（使用已存在路由） =====================
interface QuickLink { title: string; icon: string; to: string; color: string }
const quickLinks = ref<QuickLink[]>([
    { title: "菜单示例", icon: "ep:histogram", to: "/nested/menu1/menu1-1", color: "text-indigo-500" },
    { title: "二级菜单", icon: "ep:menu", to: "/nested/menu2", color: "text-emerald-500" },
    { title: "错误页 403", icon: "ep:warning-filled", to: "/error/403", color: "text-amber-500" },
    { title: "错误页 404", icon: "ep:warning-filled", to: "/error/404", color: "text-rose-500" },
]);

// ===================== 迷你折线图（Sparkline） =====================
const Sparkline = defineComponent({
    name: "Sparkline",
    props: {
        data: { type: Array as () => number[], required: true },
        width: { type: Number, default: 160 },
        height: { type: Number, default: 50 },
        color: { type: String, default: "#6366f1" }, // indigo-500
    },
    setup(props) {
        const pathD = computed(() => {
            const data = props.data as number[];
            const width = Number(props.width);
            const height = Number(props.height);
            if (!data || data.length === 0) return "";
            const max = Math.max(...data);
            const min = Math.min(...data);
            const dx = width / (data.length - 1 || 1);
            const scaleY = (v: number) => {
                if (max === min) return height / 2;
                return height - ((v - min) / (max - min)) * height;
            };
            return data
                .map((v, i) => `${i === 0 ? "M" : "L"}${i * dx},${scaleY(v)}`)
                .join(" ");
        });
        const gradientId = `g-${Math.random().toString(36).slice(2)}`;
        return () =>
            h(
                "svg",
                {
                    width: props.width,
                    height: props.height,
                    viewBox: `0 0 ${props.width} ${props.height}`,
                    xmlns: "http://www.w3.org/2000/svg",
                },
                [
                    h("defs", null, [
                        h(
                            "linearGradient",
                            { id: gradientId, x1: "0%", y1: "0%", x2: "100%", y2: "0%" },
                            [
                                h("stop", { "offset": "0%", "stop-color": props.color, "stop-opacity": "1" }),
                                h("stop", { "offset": "100%", "stop-color": props.color, "stop-opacity": "0.4" }),
                            ],
                        ),
                    ]),
                    h("path", {
                        "d": pathD.value,
                        "fill": "none",
                        "stroke": `url(#${gradientId})`,
                        "stroke-width": 2.5,
                    }),
                ],
            );
    },
});

const trendData = ref<number[]>([12, 14, 9, 16, 22, 18, 26, 24, 30, 28, 36, 40]);

// ===================== 时间线/公告 =====================
interface Notice { time: string; content: string; type?: "primary" | "success" | "warning" | "danger" | "info" }
const notices = ref<Notice[]>([
    { time: dayjs().subtract(1, "day").format("MM-DD HH:mm"), content: "完成角色权限优化与缓存策略升级", type: "success" },
    { time: dayjs().subtract(2, "day").format("MM-DD HH:mm"), content: "新增嵌套路由示例与动态标签页", type: "primary" },
    { time: dayjs().subtract(4, "day").format("MM-DD HH:mm"), content: "修复登录页验证码偶发不可见问题", type: "warning" },
]);

// ===================== 动效（VueUse Motion） =====================
const fadeUp = {
    initial: { opacity: 0, y: 20 },
    enter: { opacity: 1, y: 0, transition: { duration: 500 } },
};
</script>

<template>
    <div class="space-y-4" data-breadcrumb="false">
        <!-- 顶部欢迎区 -->
        <el-card class="bg-rounded-base overflow-hidden">
            <div
                v-motion
                :initial="fadeUp.initial"
                :enter="fadeUp.enter"
                class="flex-between-c gap-6 flex-wrap"
            >
                <div class="flex items-center gap-4 min-w-[280px]">
                    <div class="w-14 h-14 rounded-xl flex-center text-white bg-gradient-to-br from-indigo-500 to-purple-500">
                        <Icon icon="ep:home-filled" class="text-2xl" />
                    </div>
                    <div class="leading-tight">
                        <div class="text-(--el-text-color-primary) text-lg font-medium">
                            {{ greeting }}，{{ userName }}
                        </div>
                        <div class="text-(--el-text-color-regular) opacity-80 text-sm mt-1">
                            {{ nowText }}
                        </div>
                    </div>
                </div>
                <div class="flex-1 min-w-[220px]">
                    <ReTyped id="welcome-typed" :options="typedOptions" />
                </div>
            </div>
        </el-card>

        <!-- 统计卡片 -->
        <div class="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4">
            <el-card
                v-for="it in kpis"
                :key="it.title"
                shadow="hover"
                class="relative overflow-hidden"
            >
                <div class="absolute inset-0 pointer-events-none opacity-10 bg-gradient-to-r" :class="it.gradient" />
                <div class="relative flex-between-c">
                    <div>
                        <div class="text-sm text-(--el-text-color-regular)">
                            {{ it.title }}
                        </div>
                        <div class="mt-1 flex items-end gap-1">
                            <el-statistic :value="it.value" :value-style="{ fontSize: '28px', fontWeight: 600 }" />
                            <span class="text-xs text-(--el-text-color-regular)">{{ it.unit }}</span>
                        </div>
                        <div class="text-xs mt-2" :class="it.delta?.startsWith('+') ? 'text-emerald-500' : 'text-rose-500'">
                            {{ it.delta }} 对比昨日
                        </div>
                    </div>
                    <div class="w-[160px] h-[50px]">
                        <Sparkline :data="trendData" />
                    </div>
                    <div class="w-10 h-10 rounded-lg flex-center text-white bg-gradient-to-br" :class="it.gradient">
                        <Icon :icon="it.icon" />
                    </div>
                </div>
            </el-card>
        </div>

        <!-- 主体两列区 -->
        <div class="grid grid-cols-1 xl:grid-cols-3 gap-4">
            <!-- 快捷入口 -->
            <el-card class="xl:col-span-2">
                <template #header>
                    <div class="flex-between-c">
                        <span class="font-medium">快捷入口</span>
                        <el-text type="info" size="small">
                            可在此放置常用功能链接
                        </el-text>
                    </div>
                </template>
                <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3">
                    <router-link
                        v-for="q in quickLinks"
                        :key="q.to"
                        :to="q.to"
                        class="group border border-(--el-border-color) rounded-lg p-3 hover:shadow-sm transition-all bg-(--el-bg-color) dark-bg-hover"
                    >
                        <div class="flex items-center gap-3">
                            <div class="w-10 h-10 rounded-md bg-(--el-fill-color) flex-center">
                                <Icon :icon="q.icon" class="text-xl" :class="q.color" />
                            </div>
                            <div class="text-(--el-text-color-primary)">
                                {{ q.title }}
                            </div>
                        </div>
                    </router-link>
                </div>
            </el-card>

            <!-- 公告/时间线 -->
            <el-card>
                <template #header>
                    <div class="flex-between-c">
                        <span class="font-medium">最新动态</span>
                        <el-button type="primary" text size="small">
                            查看全部
                        </el-button>
                    </div>
                </template>
                <el-timeline>
                    <el-timeline-item
                        v-for="(n, idx) in notices"
                        :key="idx"
                        :timestamp="n.time"
                        :type="n.type || 'info'"
                    >
                        {{ n.content }}
                    </el-timeline-item>
                </el-timeline>
            </el-card>
        </div>
    </div>
</template>

<style scoped>
/* 让卡片圆角和暗色适配更统一 */
.el-card {
    border-radius: var(--el-border-radius-base);
}
</style>
